{% extends "base.html" %}

{% block title %}用户管理 - XbyJob{% endblock %}

{% block content %}
<div class="py-3">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-users me-2"></i>用户管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-plus me-2"></i>添加用户
        </button>
    </div>
    
    <!-- 用户列表 -->
    <div class="card">
        <div class="card-header">
            <h5><i class="fas fa-list me-2"></i>用户列表</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped" id="users-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>邮箱</th>
                            <th>管理员</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>最后登录</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td colspan="8" class="text-center">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <nav id="pagination-nav" style="display: none;">
                <ul class="pagination justify-content-center" id="pagination">
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加新用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名 *</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱 *</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码 *</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="is_admin" name="is_admin">
                        <label class="form-check-label" for="is_admin">
                            管理员权限
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addUser()">添加用户</button>
            </div>
        </div>
    </div>
</div>

<!-- 重置密码模态框 -->
<div class="modal fade" id="resetPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">重置用户密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="resetPasswordForm">
                    <input type="hidden" id="resetUserId">
                    <div class="mb-3">
                        <label for="resetUsername" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="resetUsername" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" required minlength="6">
                        <div class="form-text">密码长度不能少于6位</div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">确认密码</label>
                        <input type="password" class="form-control" id="confirmPassword" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmResetPassword()">重置密码</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 获取当前登录用户信息
const currentUser = {
    username: '{{ current_user.username }}',
    is_admin: {{ 'true' if current_user.is_admin else 'false' }}
};

$(document).ready(function() {
    loadUsers();
});

function loadUsers(page = 1) {
    $.get(`/api/admin/users?page=${page}`)
        .done(function(response) {
            if (response.success) {
                updateUsersTable(response.data.users);
                updatePagination(response.data.pagination);
            } else {
                alert('加载用户列表失败: ' + response.message);
            }
        })
        .fail(function() {
            alert('加载用户列表失败');
        });
}

function updateUsersTable(users) {
    const tbody = $('#users-table tbody');
    tbody.empty();
    
    if (users.length === 0) {
        tbody.append('<tr><td colspan="8" class="text-center">暂无用户</td></tr>');
        return;
    }
    
    users.forEach(function(user) {
        const adminBadge = user.is_admin ? 
            '<span class="badge bg-danger">管理员</span>' : 
            '<span class="badge bg-secondary">普通用户</span>';
        
        const statusBadge = user.is_active ? 
            '<span class="badge bg-success">正常</span>' : 
            '<span class="badge bg-danger">禁用</span>';
        
        const createdAt = new Date(user.created_at).toLocaleString();
        const lastLogin = user.last_login ? new Date(user.last_login).toLocaleString() : '从未登录';
        
        // 构建操作按钮，admin账户不能被禁用，用户不能禁用自己
        let actions = '';
        if (user.username !== 'admin' && user.id !== currentUser.id) {
            const toggleAction = user.is_active ? 
                `<button class="btn btn-sm btn-warning" onclick="toggleUser(${user.id})">禁用</button>` :
                `<button class="btn btn-sm btn-success" onclick="toggleUser(${user.id})">启用</button>`;
            actions = toggleAction;
        }
        // 重置密码按钮权限：admin可重置所有账户，管理员只能重置普通用户
        if (!user.is_admin) {
            // 非管理员用户：所有管理员都可以重置密码
            actions += ` <button class="btn btn-sm btn-info" onclick="resetPassword(${user.id}, '${user.username}')">重置密码</button>`;
            // 只有不是当前用户自己时才显示删除按钮
            if (user.id !== currentUser.id) {
                actions += ` <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id}, '${user.username}')">删除</button>`;
            }
        } else if (user.is_admin) {
            // 管理员用户：只有admin可以重置其他管理员密码
            if (currentUser.username === 'admin') {
                actions += ` <button class="btn btn-sm btn-info" onclick="resetPassword(${user.id}, '${user.username}')">重置密码</button>`;
            }
            // 如果当前登录用户是admin，则可以删除其他管理员（但不能删除自己）
            if (currentUser.username === 'admin' && user.id !== currentUser.id) {
                actions += ` <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id}, '${user.username}')">删除</button>`;
            }
        }
        tbody.append(`
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${adminBadge}</td>
                <td>${statusBadge}</td>
                <td>${createdAt}</td>
                <td>${lastLogin}</td>
                <td>
                    <div class="btn-group" role="group">
                        ${actions}
                    </div>
                </td>
            </tr>
        `);
    });
}

function updatePagination(pagination) {
    const nav = $('#pagination-nav');
    const ul = $('#pagination');
    
    if (pagination.pages <= 1) {
        nav.hide();
        return;
    }
    
    nav.show();
    ul.empty();
    
    // 上一页
    if (pagination.has_prev) {
        ul.append(`<li class="page-item">
            <a class="page-link" href="#" onclick="loadUsers(${pagination.page - 1})">上一页</a>
        </li>`);
    }
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        const active = i === pagination.page ? 'active' : '';
        ul.append(`<li class="page-item ${active}">
            <a class="page-link" href="#" onclick="loadUsers(${i})">${i}</a>
        </li>`);
    }
    
    // 下一页
    if (pagination.has_next) {
        ul.append(`<li class="page-item">
            <a class="page-link" href="#" onclick="loadUsers(${pagination.page + 1})">下一页</a>
        </li>`);
    }
}

function addUser() {
    const form = $('#addUserForm');
    const formData = {
        username: form.find('#username').val(),
        email: form.find('#email').val(),
        password: form.find('#password').val(),
        is_admin: form.find('#is_admin').is(':checked')
    };
    
    if (!formData.username || !formData.email || !formData.password) {
        showAlert('请填写所有必填字段', 'warning');
        return;
    }
    
    $.ajax({
        url: '/api/admin/users',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                showAlert('用户添加成功', 'success');
                $('#addUserModal').modal('hide');
                // 确保移除模态框遮罩层
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                form[0].reset();
                loadUsers();
            } else {
                showAlert('添加用户失败: ' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('添加用户失败', 'danger');
        }
    });
}

function toggleUser(userId) {
    if (!confirm('确定要更改用户状态吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/admin/users/${userId}/toggle`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                showAlert('用户状态更新成功', 'success');
                loadUsers();
            } else {
                showAlert('更新用户状态失败: ' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('更新用户状态失败', 'danger');
        }
    });
}

function deleteUser(userId, username) {
    if (!confirm(`确定要删除用户 "${username}" 吗？\n\n此操作将不可恢复地删除该用户及其所有数据（包括任务、脚本、执行记录等）！`)) {
        return;
    }
    
    $.ajax({
        url: `/api/admin/users/${userId}`,
        method: 'DELETE',
        success: function(response) {
            if (response.success) {
                showAlert('用户删除成功', 'success');
                loadUsers();
            } else {
                showAlert('删除用户失败: ' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('删除用户失败', 'danger');
        }
    });
}

function resetPassword(userId, username) {
    $('#resetUserId').val(userId);
    $('#resetUsername').val(username);
    $('#newPassword').val('');
    $('#confirmPassword').val('');
    $('#resetPasswordModal').modal('show');
}

function confirmResetPassword() {
    const userId = $('#resetUserId').val();
    const newPassword = $('#newPassword').val();
    const confirmPassword = $('#confirmPassword').val();
    
    if (!newPassword || newPassword.length < 6) {
        showAlert('密码长度不能少于6位', 'warning');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showAlert('两次输入的密码不一致', 'warning');
        return;
    }
    
    $.ajax({
        url: `/api/admin/users/${userId}/reset_password`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({new_password: newPassword}),
        success: function(response) {
            if (response.success) {
                showAlert('密码重置成功', 'success');
                $('#resetPasswordModal').modal('hide');
                // 确保移除模态框遮罩层
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
            } else {
                showAlert('重置密码失败: ' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('重置密码失败', 'danger');
        }
    });
}

function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    if (typeof window.showMessage === 'function') {
        // 映射类型到Toast支持的类型
        let toastType = type;
        switch(type) {
            case 'danger':
                toastType = 'error';
                break;
            case 'warning':
                toastType = 'warning';
                break;
            case 'success':
                toastType = 'success';
                break;
            default:
                toastType = 'info';
        }
        showMessage(message, toastType, 3000);
    } else {
        // 如果全局函数不可用，回退到原来的实现
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('body').prepend(alertHtml);
        
        // 3秒后自动消失
        setTimeout(function() {
            $('.alert').alert('close');
        }, 3000);
    }
}
</script>
{% endblock %}